<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="所属机构" prop="tenantId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.tenantId"-->
      <!--          placeholder="请输入所属机构"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="机构名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入机构名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="编码" prop="templateCode">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.templateCode"-->
      <!--          placeholder="请输入编码"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="条件名称" prop="conditionName">
        <el-input
          v-model="queryParams.conditionName"
          placeholder="请输入条件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消息类型" prop="messageType">
        <el-select v-model="queryParams.messageType" placeholder="请选择消息类型">
          <el-option label="内部消息" value="1"></el-option>
          <el-option label="外部消息" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:pushCondition:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pushConditionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="机构名称" align="center" prop="tenantName"/>
      <el-table-column label="编码" align="center" prop="pushConditionCode"/>
      <el-table-column label="条件名称" align="center" prop="conditionName"/>
      <el-table-column label="消息类型" align="center" prop="messageType">
        <template slot-scope="scope">
          {{ scope.row.messageType === '1' ? '内部消息' : '外部消息' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="conditionState">
        <template slot-scope="scope">
          {{ scope.row.conditionState === '0' ? '启用' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:pushCondition:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:pushCondition:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改推送条件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="适用机构" prop="tenantId">
          <el-select
            v-model="form.tenantId"
            filterable
            remote
            placeholder="输入机构名称搜索"
            :remote-method="getTenantList"
            :loading="getTenantListLoading">
            <el-option
              v-for="item in tenantList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="消息类型" prop="messageType">
          <el-radio-group v-model="form.messageType" @change="changeMessageType">
            <el-radio label='1'>
              内部消息
              <el-tooltip effect="dark" content="内部消息包括：企业微信、钉钉、商家小程序消息" placement="top">
                <i class="el-icon-question" style="font-size: 12px; position: relative; top: -10px;opacity: 0.5;"></i>
              </el-tooltip>
            </el-radio>
            <el-radio label='2'>
              外部消息
              <el-tooltip effect="dark" content="外部消息包括：租客小程序" placement="top">
                <i class="el-icon-question" style="font-size: 12px; position: relative; top: -10px;opacity: 0.5;"></i>
              </el-tooltip>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="条件名称" key="conditionType" prop="conditionType">
          <el-select v-model="form.conditionType" style="width: 100%;"
                     @change="changeConditionType($event,dict.type.condition_type)">
            <el-option
              v-for="dict in conditionTypeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="消息状态" prop="conditionState">
          <el-radio-group v-model="form.conditionState">
            <el-radio label='0'>启用</el-radio>
            <el-radio label='1'>禁用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPushCondition,
  delPushCondition,
  getPushCondition,
  listPushCondition,
  pageDepartment,
  updatePushCondition,
} from "@/api/messageCenter/pushCondition";
import Template from "@/views/contract/template/index.vue";

export default {
  name: "PushCondition",
  components: {Template},
  dicts: ["condition_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 推送条件信息表格数据
      pushConditionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: null,
        tenantName: null,
        pushConditionCode: '',
        conditionType: null,
        conditionName: null,
        messageType: null,
        conditionState: null,
        operatorId: null,
      },
      // 机构列表
      tenantList: [],
      // 机构列表加载状态
      getTenantListLoading: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantId: [
          {required: true, message: "使用机构不能为空", trigger: "blur"}
        ],
        messageType: [
          {required: true, message: "请选择消息类型", trigger: "blur"}
        ],
        conditionType: [
          {required: true, message: "请选择条件名称", trigger: "blur"}
        ],
        conditionState: [
          {required: true, message: "请选择状态", trigger: "blur"}
        ],
      }
    };
  },
  computed: {
    conditionTypeList: {
      get() {
        console.log('dicts', this.dict.type.condition_type)
        if (this.form.messageType === '1') {
          return this.dict.type.condition_type.filter(item => item.value < 100)
        }else if (this.form.messageType === '2') {
          return this.dict.type.condition_type.filter(item => item.value >= 100)
        }
        return []
      }
    }
  },
  created() {
    this.getTenantList()
    this.getList();
  },
  methods: {
    /** 查询推送条件信息列表 */
    getList() {
      this.loading = true;
      listPushCondition(this.queryParams).then(response => {
        this.pushConditionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取机构列表
    getTenantList(data) {
      console.log('data', data)
      this.getTenantListLoading = true;
      let params = {
        pageNum: 1,
        pageSize: 10,
        tenantName: data
      }
      pageDepartment(params).then(response => {
        console.log('response', response)
        this.tenantList = response.rows.map(item => {
          return {
            value: item.tenantId,
            label: item.tenantName
          }
        })
        this.getTenantListLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pushConditionId: null,
        tenantId: null,
        tenantName: null,
        pushConditionCode: '',
        conditionType: null,
        conditionName: null,
        messageType: '1',
        conditionState: '0',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pushConditionId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加推送条件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pushConditionId = row.pushConditionId || this.ids
      getPushCondition(pushConditionId).then(response => {
        this.getTenantList(response.data.tenantName)
        this.form = response.data;
        this.open = true;
        this.title = "修改推送条件信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pushConditionId != null) {
            updatePushCondition(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPushCondition(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pushConditionIds = row.pushConditionId || this.ids;
      this.$modal.confirm('是否确认删除此数据项？').then(function () {
        return delPushCondition(pushConditionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/pushCondition/export', {
        ...this.queryParams
      }, `pushCondition_${new Date().getTime()}.xlsx`)
    },
    //消息类型切换
    changeMessageType(val) {
      this.form.conditionType = null;
      this.form.conditionName = null;
    },
    //条件名称切换
    changeConditionType(val, dict) {
      this.form.conditionName = dict.find(item => item.value === val).label;
    },
  }
};
</script>
